//
//  XLOldMainTapViewController.m
//  XiangLove
//
//  Created by feng song on 2017/12/14.
//  Copyright © 2017年 BAOMIHUA.COM. All rights reserved.
//

#import "XLOldMainTapViewController.h"
#import "ConversationListViewController.h"
 
#import <Masonry.h>
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import <UIImageView+YYWebImage.h>
#import "XLHTTPSessionManager+Camgirl.h"
#import <ReactiveCocoa.h>

#import "XLCamgirlView.h"
#import "NewCamgirlModel.h"
#import "XLMineViewController.h"
#import "TopUpViewController.h"
#import "CallMakeViewController.h"
#import <BMHVideoPlayerView.h>
#import <BMHVideoConfig.h>
#import <BMHVideoPlayerControl.h>
#import "HomeCallModel.h"
#import "XLHTTPSessionManager+UserInfo.h"
#import "XLHTTPSessionManager+Analytics.h"
#import "XLLiveInforView.h"
#import "XLNewTopUpView.h"
#import "XLTopUpModel.h"
#import "WeixinHelper.h"
#import "BMHAlertView.h"
#import <StoreKit/StoreKit.h>   //添加内购系统框架
#import "BMHStoreObserver.h"
#import <ImSDK/TIMFriendshipManager.h>
#import "IMAChatViewController.h"
#import "XLBeautyView.h"
#import "BMHPromptView.h"
#define DURATION 0.7f

@interface XLOldMainTapViewController ()<BMHVideoPlayerControlDelegate,XLNewTopUpDelegate,UIGestureRecognizerDelegate>
@property (nonatomic,strong) BMHVideoPlayerView     *playerView;
@property (nonatomic,strong) UIImageView            *oldHostImgView;
@property (nonatomic,weak  ) XLLiveInforView        *livingInfoView;
@property (nonatomic,strong) UIView                 *bottomView;
@property (nonatomic,strong) UILabel                *nickName;
@property (nonatomic,strong) UILabel                *addrss;
@property (nonatomic,strong) UILabel                *callTimes;
@property (nonatomic,strong) UIButton               *messageBtn;
@property (nonatomic,strong) UIButton               *mineBtn;
@property (nonatomic,strong) UIView                 *VideobgView;
@property (nonatomic,strong) UIButton               *videoCall;

@property (nonatomic,strong) NSArray                *dataArray;
@property (nonatomic,assign) NSInteger               pageIndex;
@property (nonatomic,assign) NSInteger               hostIndex;
@property (nonatomic,assign) BOOL                    isBeginSlid;//记录开始触摸的方向
@property (nonatomic,strong) UIView                 *redPoint;
@property (nonatomic,strong) XLNewTopUpView         *topUpview;
@property (nonatomic,strong) NSMutableArray         *topUpMoneyArr;
@property (nonatomic,strong) NSMutableArray         *topUpJDArr;
@property (nonatomic,copy  ) NSString               *myMoney;
@property (nonatomic,strong) NSDictionary           *zfbDic;
@property (nonatomic,copy  ) NSString               *actionType;
@property (nonatomic,copy  ) NSString               *payorder;//支付宝订单号
@property (nonatomic,strong) NewCamgirlModel        *currentCamgirlModel;
@property (nonatomic,strong) XLUserInfoModel        *userInfoModel;
@property (nonatomic,assign) BOOL                    shouldRefresh;
@property (nonatomic,strong) BMHAlertView           *alertView;
@property (nonatomic,strong) UIImageView            *imageView;
@property (nonatomic,strong) UILabel                *alterTitle;
@property (nonatomic,strong) UIView                 *bottomupView;
@property (nonatomic,copy  ) NSString               *productIds;
@property (nonatomic,strong) UILabel                *hostState;
@property (nonatomic,strong) XLBeautyView           *beautyView;
@property (nonatomic,strong) BMHPromptView          *promptView;
@property (nonatomic,strong) NSTimer                *hintTimer;
@property (nonatomic,strong) NSTimer                *hintSecondTimer;
@property (nonatomic,strong) UITapGestureRecognizer *Viewtap;
@property (nonatomic,strong) UITapGestureRecognizer *playtap;
@property (nonatomic,strong) UIImageView            *hintSecondView;

@property (nonatomic, weak) RACDisposable *disposable;
@property (nonatomic, assign) BOOL isAppear;
@end

@implementation XLOldMainTapViewController


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
        
        self.hintTimer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(startHintView) userInfo:nil repeats:NO];
        [self hintView];
    }
    self.isAppear = YES;
    [self makeData];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.playerView play];
    [self analyticsEvent1];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refresh) object:nil];
    if (self.shouldRefresh) {
        [self makeData];
        self.shouldRefresh = NO;
    }
}



- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.isAppear = NO;
    [self.playerView shutDownPlayer];
    [self.disposable dispose];
//    [self.hintTimer invalidate];
//    self.hintTimer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    self.zfbDic        = [NSDictionary   dictionary];
    self.topUpMoneyArr = [NSMutableArray array];
    self.topUpJDArr    = [NSMutableArray array];
    
    _beautyView = [[XLBeautyView alloc] init];
    _beautyView.hidden = YES;
    [self.view addSubview:_beautyView];
    [_beautyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self makeUI];
    [self addObserver];
    [self refreshUserInfo];
    //[self makeData];
}

- (void)addObserver {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"zhifusuccess" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self analyticsEvent10];
        [self refreshUserInfo];
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:BMHRefreshUserInfo object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self refreshUserInfo];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"repeatSelectRecommand" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self refreshUserInfo];
        [self makeData];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self performSelector:@selector(refresh) withObject:nil afterDelay:60];
        UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        }];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillEnterForegroundNotification object:nil] subscribeNext:^(id x) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refresh) object:nil];
        if (self.shouldRefresh) {
            [self makeData];
            self.shouldRefresh = NO;
        }
    }];
}

- (void)refresh {
    if (self.navigationController.topViewController == self) {
        self.shouldRefresh = YES;
    }
}

-(void)makeUI
{
    _oldHostImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, XQScreenW, XQScreenH)];
    _oldHostImgView.clipsToBounds = YES;
    _oldHostImgView.contentMode = UIViewContentModeScaleAspectFill;
    _oldHostImgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [_oldHostImgView setContentScaleFactor:[[UIScreen mainScreen] scale]];
    [self.view addSubview:_oldHostImgView];
    
    _bottomupView = [[UIView alloc] initWithFrame:CGRectMake(0,XQScreenH-200,XQScreenW,200)];
    [self.view addSubview:_bottomupView];
    CAGradientLayer *gradient = [CAGradientLayer layer];
    
    gradient.frame = _bottomupView.bounds;
    gradient.colors = [NSArray arrayWithObjects:
                       (id)RGBA_HEX(0x000000, 0).CGColor,
                       (id)RGBA_HEX(0x000000, 0.6).CGColor,
                       nil];
    gradient.startPoint = CGPointMake(1, 0);
    gradient.endPoint = CGPointMake(1, 1);
    gradient.locations = @[@0.2];
    [_bottomupView.layer addSublayer:gradient];
    
    BMHVideoConfig *config = [[BMHVideoConfig alloc] init];
    _playerView = [[BMHVideoPlayerView alloc] initWithFrame:self.view.frame delegate:self config:config];
    _playerView.hidePlayControl = YES;
    _playerView.coverView.contentMode = UIViewContentModeScaleAspectFill;
    _playerView.coverView.image = [UIImage imageNamed:@""];
    [_playerView.tx_player setRenderMode:RENDER_MODE_FILL_SCREEN];
    [self.view addSubview:self.playerView];
    [_playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self bringUpView:self.view];

    XLLiveInforView * liveingInforView = [[XLLiveInforView alloc] initWithFrame:CGRectMake(0, 0, XQScreenW, XQScreenH)];
    [self.view addSubview:liveingInforView];
    self.livingInfoView = liveingInforView;
    
    UIView *  bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,XQScreenH-200, XQScreenW,148)];
    [self.livingInfoView addSubview:bottomView];
    self.bottomView = bottomView;
    
    _nickName = [[UILabel alloc] init];
    _nickName.textColor           = kWhiteColor;
    _nickName.font                = [UIFont boldSystemFontOfSize:30];
    _nickName.layer.masksToBounds = YES;
    _nickName.layer.cornerRadius  = 10;
    [self.bottomView addSubview:_nickName];
    
    _hostState = [[UILabel alloc] init];
    _hostState.textColor = kWhiteColor;
    _hostState.font      = kSetFont(10);
    _hostState.layer.masksToBounds = YES;
    _hostState.layer.cornerRadius = 10;
    _hostState.textAlignment = NSTextAlignmentCenter;
    [self.bottomView addSubview:_hostState];
    
    _addrss = [[UILabel alloc] initWithFrame:CGRectMake(15,93,100,24)];
    _addrss.backgroundColor     = RGBA_HEX(0x000000, 0.3);
    _addrss.textColor           = kWhiteColor;
    _addrss.font                = [UIFont systemFontOfSize:12.0];
    _addrss.layer.masksToBounds = YES;
    _addrss.layer.cornerRadius  = 12;
    _addrss.textAlignment       = NSTextAlignmentCenter;
    [self.bottomView addSubview:_addrss];
    
    _callTimes = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.addrss.frame)+9,CGRectGetMinY(self.addrss.frame), 120, 24)];
    _callTimes.backgroundColor = RGBA_HEX(0x000000, 0.3);
    _callTimes.textColor = kWhiteColor;
    _callTimes.font = [UIFont systemFontOfSize:12.0];
    _callTimes.layer.masksToBounds = YES;
    _callTimes.layer.cornerRadius = 12;
    _callTimes.textAlignment = NSTextAlignmentCenter;
    [self.bottomView addSubview:_callTimes];
    
    _videoCall = [[UIButton alloc] init];
    _videoCall.layer.masksToBounds = YES;
    //[_videoCall setImage:[UIImage imageNamed:@"home_but_dial_n"] forState:UIControlStateNormal];
    [_videoCall addTarget:self action:@selector(videoChat:) forControlEvents:UIControlEventTouchUpInside];
    [self.livingInfoView addSubview:_videoCall];
    [_videoCall mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.livingInfoView);
        make.bottom.equalTo(self.livingInfoView.mas_bottom).offset(-69);
        make.size.mas_equalTo(CGSizeMake(100, 80));
        
    }];
    
    /*
    _messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(25, XQScreenH-25-18,41, 25)];
    [_messageBtn setTitle:@"消息" forState:UIControlStateNormal];
    [_messageBtn setTitleColor:RGBA_HEX(0xffffff,0.7) forState:UIControlStateNormal];
    _messageBtn.titleLabel.font = [UIFont systemFontOfSize:18.0];
    [_messageBtn addTarget:self action:@selector(messageAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_messageBtn];
    
    _redPoint = [[UIView alloc] init];
    _redPoint.hidden = YES;
    _redPoint.layer.cornerRadius = 4;
    _redPoint.backgroundColor = RGB_HEX(0xff4a45);
    [_messageBtn addSubview:_redPoint];
    [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(8, 8));
        make.center.equalTo(_messageBtn).centerOffset(CGPointMake(18, -9));
    }];
    
    _mineBtn = [[UIButton alloc] initWithFrame:CGRectMake(XQScreenW-25-41, XQScreenH-25-18, 41, 25)];
    [_mineBtn setTitle:@"我的" forState:UIControlStateNormal];
    _mineBtn.titleLabel.font = [UIFont systemFontOfSize:18.0];
    [_mineBtn setTitleColor:RGBA_HEX(0xffffff,0.7) forState:UIControlStateNormal];
    [_mineBtn addTarget:self action:@selector(mineBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_mineBtn];
    */
    //[self videoChatView];
    
    
}

#pragma mark - getter
- (BMHPromptView *)promptView {
    if (_promptView == nil) {
        _promptView = [[BMHPromptView alloc] initWithImage:[UIImage imageNamed:@"common_img_wifi_d"]];
        [self.view addSubview:_promptView];
        [_promptView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(200, 215));
            make.center.equalTo(self.view);
        }];
        @weakify(self);
        _promptView.touchBlock = ^{
            @strongify(self);
            [self makeData];
        };
    }
    return _promptView;
}

-(void)startHintView
{
    _alertView.alpha = 0;
    _alertView.contentView.alpha = 0;
    _imageView.alpha = 0;
}

- (void)hintView {
    static dispatch_once_t disOnce;
    dispatch_once(&disOnce, ^ {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
            
            _alertView = [[BMHAlertView alloc] initWithOverType:BMHAlertViewTypePopover touchShadeClose:YES];
            _alertView.contentView.backgroundColor = [UIColor clearColor];
            
            _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"home_img_shoushi_d"]];
            [_alertView.contentView addSubview:_imageView];
            [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(_alertView.contentView);
            }];
            
            [[UIApplication sharedApplication].keyWindow addSubview:_alertView];
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(panTouch:)];
            [_alertView.contentView addGestureRecognizer:tapGesture];
        }
    });
}

- (void)panTouch:(UITapGestureRecognizer *)tap {
    [self.hintTimer invalidate];
    self.hintTimer = nil;
    _alertView.alpha = 0;
    _alertView.contentView.alpha = 0;
    _imageView.alpha = 0;
}

-(void)hintViewSecond
{
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
//
////        _alertView = [[BMHAlertView alloc] initWithOverType:BMHAlertViewTypeFade touchShadeClose:YES];
////        _alertView.contentView.backgroundColor = kClearColor;
////        _imageView =[[UIImageView alloc] init];
////        _imageView.image = [UIImage imageNamed:@"home_img_dial_d"];
////        [_alertView.contentView addSubview:_imageView];
////        [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
////            make.right.equalTo(_alertView.contentView.mas_right).offset(-5);
////            make.bottom.equalTo(_alertView.contentView.mas_bottom).offset(-109);
////            make.size.mas_equalTo(CGSizeMake(237, 137));
////        }];
////        [[UIApplication sharedApplication].keyWindow addSubview:_alertView];
////        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewTouch:)];
////        [_alertView.contentView addGestureRecognizer:tapGesture];
//        
//
//    }
    _hintSecondView =[[UIImageView alloc] init];
    _hintSecondView.image = [UIImage imageNamed:@"home_img_dial_d"];
    [self.view addSubview:_hintSecondView];
    [_hintSecondView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-5);
        make.bottom.equalTo(self.view.mas_bottom).offset(-109);
        make.size.mas_equalTo(CGSizeMake(237, 137));
    }];
   
    
}

- (void)imageViewTouch:(UITapGestureRecognizer *)tap {
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
    _alertView.alpha = 0;
    _alertView.contentView.alpha = 0;
    _imageView.alpha = 0;
    
}

- (void)refreshUserInfo {
    [[[XLHTTPSessionManager sharedManager] getUserInfoWithUserId:[[XLAccountManager shareInstance] model].Id secretKey:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
        self.userInfoModel = x;
        [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
        [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
        [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
        self.userInfoModel.SecretKey = [[XLAccountManager shareInstance] model].SecretKey;
        [[XLAccountManager shareInstance] updateUserInfo:self.userInfoModel];
    } error:^(NSError *error) {
        
    }];
}

-(void)videoChatView
{
    /*
    UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake((XQScreenW-160)/2, XQScreenH-42-14, 160, 42)];
    bgView.layer.masksToBounds = YES;
    bgView.layer.cornerRadius = 20;
    CAGradientLayer *gradient = [CAGradientLayer layer];
    
    gradient.frame = bgView.bounds;
    gradient.colors = [NSArray arrayWithObjects:
                       (id)RGB_HEX(0xff5f6d).CGColor,
                       (id)RGB_HEX(0xffc371).CGColor,
                       nil];
    gradient.startPoint = CGPointMake(0, 1);
    gradient.endPoint = CGPointMake(1, 1);
    gradient.locations = @[@0.3];
    [bgView.layer addSublayer:gradient];
    [self.view addSubview:bgView];
    self.VideobgView = bgView;
    
    _videoCall = [[UIButton alloc] initWithFrame:CGRectMake(0,0,160,42)];
    _videoCall.layer.masksToBounds = YES;
    _videoCall.layer.cornerRadius = 20;
    _videoCall.titleLabel.font = [UIFont systemFontOfSize:16.0];
    if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue]) {
        [_videoCall setTitle:@"和她聊天" forState:UIControlStateNormal];
    } else {
        [_videoCall setTitle:@"和她视频" forState:UIControlStateNormal];
    }
    [_videoCall setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_videoCall setImage:[UIImage imageNamed:@"xinliao_icon_shiping"] forState:UIControlStateNormal];
    _videoCall.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,10);
    [_videoCall addTarget:self action:@selector(videoChat:) forControlEvents:UIControlEventTouchUpInside];
    [self.VideobgView addSubview:_videoCall];
    */
    
    
    
}

-(void)makeData
{
    [self.disposable dispose];
    self.pageIndex = 1;
    self.beautyView.hidden = NO;
    self.disposable = [[[XLHTTPSessionManager sharedManager] getNewCamgirlBeautyListPageIndex:self.pageIndex type:@1 userID:[[XLAccountManager shareInstance] model].Id andSign:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
        if (self.isAppear == NO) return ;
        [_promptView removeFromSuperview];
        _promptView = nil;
        [self viewsIsHidden:NO];
        self.beautyView.hidden = YES;
        self.dataArray = x;
        if (self.dataArray.count > 0) {
            
            self.currentCamgirlModel = self.dataArray.firstObject;
            [self playVideoWithCamgirlModel:self.currentCamgirlModel];
            self.hostIndex = 0;
        }
    } error:^(NSError *error) {
        NSLog(@"错误---%ld",(long)error.code);
        self.beautyView.hidden = YES;
        if (error.code != 1003) {

            self.promptView.hidden = NO;
            [self viewsIsHidden:YES];
        }
        
        
    }];
    
    [BMHHTTPSession GETBMHVideo:@"/api/v1/VideoChatInfo/GetRechareInfo" paraments:@{@"type":@"1"} success:^(id  _Nullable JSON) {
        
        NSLog(@"新用户列表:%@",JSON);
        if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue]  == YES) {
            
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"6",@"30",@"50",@"108",nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"42",@"210",@"350",@"756",nil];
            self.myMoney       = self.topUpMoneyArr[0];
            
        }else{
            
            [self getTopupList:JSON[@"data"]];
        }
        
    } failure:^(NSError * _Nullable error) {
        NSLog(@"%@", error);
        [MBProgressHUD showContent:@"加载失败" toView:self.view];
    }];
    
    @weakify(self);
    [RACObserve([IMAPlatformxl sharedInstance].conversationMgr, unReadMessageCount) subscribeNext:^(id x) {
        @strongify(self);
        self.redPoint.hidden = [x integerValue] <= 0;
    }];
    
}

-(void)getTopupList:(NSMutableArray *)arr
{
    for (int i = 0; i < arr.count; i++) {
        
        XLTopUpModel * topupMd = [XLTopUpModel modelWithDictionary:arr[i]];
        [self.topUpMoneyArr addObject:topupMd.money];
        [self.topUpJDArr    addObject:topupMd.jindou];
        if (i == 0) {
            self.myMoney = topupMd.money;
        }
    }
    
}

#pragma mark - 主播展示
- (void)playVideoWithCamgirlModel:(NewCamgirlModel *)model
{
    [self analyticsEvent1];
    self.Viewtap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(videoChat:)];
    self.Viewtap.delegate = self;
    [self.view addGestureRecognizer:self.Viewtap];
    
    if (self.playerView.superview == nil) {
        [self.view addSubview:self.playerView];
        [self.playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        [self bringUpView:self.view];
    }
    BMHVideoConfig *config = [[BMHVideoConfig alloc] init];
    [self.playerView.coverView setImageWithURL:[NSURL URLWithString:model.VideoImg] placeholder:[UIImage imageNamed:@""]];
    
    [self.playerView reloadContentUrl:model.VideoUrl config:config];
    
    self.playtap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(videoChat:)];
    self.playtap.delegate = self;
    [self.playerView addGestureRecognizer:self.playtap];
    [self.playerView.playControl removeFromSuperview];
    [self.playerView.tx_player setRenderMode:RENDER_MODE_FILL_SCREEN];
    
    
    [self.oldHostImgView setImageWithURL:[NSURL URLWithString:model.VideoImg] placeholder:[UIImage imageNamed:@""]];
    [_videoCall setImage:[UIImage imageNamed:@"home_but_dial_n"] forState:UIControlStateNormal];
    
    CGSize nickNameSize = [self sizeWithText:model.NickName font:[UIFont boldSystemFontOfSize:30] maxSize:CGSizeMake(MAXFLOAT, 42)];
    
    if (nickNameSize.width > 0) {
        
        self.nickName.frame = CGRectMake(15,47,nickNameSize.width+10,42);
        self.nickName.text  = model.NickName;
        
    }else{
        self.nickName.frame = CGRectMake(0, 0, 0, 0);
        self.nickName.text  = @"";
    }
    
    
    if ([model.OnlineStatus isEqualToString:@"0"]) {
        self.hostState.backgroundColor = RGB_HEX(0x9395a2);
        self.hostState.text = @"离线";
    }else if ([model.OnlineStatus isEqualToString:@"1"])
    {
        self.hostState.backgroundColor = RGB_HEX(0x44db5e);
        self.hostState.text = @"在线";
        
    }else if ([model.OnlineStatus isEqualToString:@"2"]){
        self.hostState.text = @"在线";
        self.hostState.backgroundColor = RGB_HEX(0x44db5e);
    }
    [self.hostState mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.nickName.mas_right);
        make.centerY.equalTo(self.nickName);
        make.size.mas_equalTo(CGSizeMake(36, 20));
    }];
    
    CGSize addrssSize = [self sizeWithText:model.HostCity font:[UIFont systemFontOfSize:12.0] maxSize:CGSizeMake(MAXFLOAT, 24)];
    if (addrssSize.width > 0) {
        self.addrss.frame = CGRectMake(15,93,addrssSize.width+10,24);
        self.addrss.text  = model.HostCity;
        
    }else{
        
        self.addrss.frame = CGRectMake(0, 0, 0, 0);
        self.addrss.text  = @"";
    }
    
    CGSize callTimesSize = [self sizeWithText:[NSString stringWithFormat:@"已经通话%@分钟",model.WhenLong] font:[UIFont systemFontOfSize:12.0] maxSize:CGSizeMake(MAXFLOAT, 24)];
    if (addrssSize.width >0 ) {
        self.callTimes.frame = CGRectMake(CGRectGetMaxX(self.addrss.frame)+9,CGRectGetMinY(self.addrss.frame), callTimesSize.width+10, 24);
        self.callTimes.text = [NSString stringWithFormat:@"已经通话%@分钟",model.WhenLong];
    }else{
        
        self.callTimes.frame = CGRectMake(0, 0, 0, 0);
        self.callTimes.text  = @"";
    }
    
}

#pragma mark - UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if ([touch.view isDescendantOfView:self.topUpview]) {
        return NO;
    }
    
    return YES;
    
}

-(void)bringUpView:(UIView *)view
{
    [view bringSubviewToFront:self.beautyView];
    [view bringSubviewToFront:self.bottomupView];
    [view bringSubviewToFront:self.livingInfoView];
    [view bringSubviewToFront:self.nickName];
    [view bringSubviewToFront:self.hostState];
    [view bringSubviewToFront:self.addrss];
    [view bringSubviewToFront:self.callTimes];
    [view bringSubviewToFront:self.videoCall];
    [view bringSubviewToFront:self.hintSecondView];
    [view bringSubviewToFront:self.bottomView];
    
    
    
}

-(void)viewsIsHidden:(BOOL)isHidden
{
    self.beautyView.hidden      = isHidden;
    self.bottomupView.hidden    = isHidden;
    self.livingInfoView.hidden  = isHidden;
    self.nickName.hidden        = isHidden;
    self.hostState.hidden       = isHidden;
    self.addrss.hidden          = isHidden;
    self.callTimes.hidden       = isHidden;
    self.callTimes.hidden       = isHidden;
    self.videoCall.hidden       = isHidden;
    self.bottomView.hidden      = isHidden;
    
}

#pragma mark -VideoChatEvent
-(void)videoChat:(UIButton *)sender
{
    self.hintSecondView.hidden = YES;
    [self.hintSecondTimer invalidate];
    self.hintSecondTimer = nil;
    if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue] == YES) {
        NewCamgirlModel *model = self.dataArray[self.hostIndex];
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[model.UserId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
    } else {
        if ([[[XLAccountManager shareInstance] model].AccountBalanceString floatValue] > 0) {
            [self analyticsEvent2];
            [self videoChatWithCamgirl:self.dataArray[self.hostIndex]];
        } else {
            [self analyticsEvent5];
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
        }
    }
}

- (void)videoChatWithCamgirl:(NewCamgirlModel *)model {
    BMHLog(@"和%@去视频聊天", model.NickName);
    if ([model.UserId isEqualToString:[[XLAccountManager shareInstance] model].Id]) {
        [MBProgressHUD showContent:@"不能自嗨哟！" toView:self.view];
        return;
    }
    NSString * useridStr = model.UserId;
    NSDate * senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
    [MBProgressHUD showMessage:@"" toView:self.view];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
        NSLog(@"=====dd个人资料json====%@",JSON);
        NSString  *status  =  JSON[@"result"][@"errcode"];
        [MBProgressHUD hideHUDForView:self.view];
        if ([F(@"%@", status) isEqualToString:@"803"]) {
            [MBProgressHUD showContent:@"对方取消了视频通话功能" toView:self.view];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:model.UserId];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
                
            }];
        }else{
            HomeCallModel *model = [[HomeCallModel alloc] initWithDict:JSON[@"result"][@"data"]];
            if ([self checkCameraAuthorization]) {
                [self chatWithModel:model];
            }
        }
    } failure:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

#pragma mark -XLNewTopUpDelegate
-(void)XLSelectedJD:(UIButton *)selectedBtn
{
    
    self.myMoney = [self.topUpMoneyArr objectAtIndex:selectedBtn.tag];
    BMHLog(@"选择了%@",self.myMoney);
}


-(void)XLNewtestTopup
{
    self.myMoney = @"1";
}

//微信充值
-(void)XLNewWXZHIFU:(UIButton *)wxBtn;
{
    
    if (!([self.myMoney integerValue] > 0)) {
        
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
        
    } else {
        [self analyticsEvent9];
        [[WeixinHelper sharedWeixinHelper] getUrlWithWXMoney:self.myMoney Months:@"0" TranstypeId:@"1" RemarksInfo:RemarksRose KKOrder:@"" kkUserid:@""];
        
        self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
        
    }
    
}

- (void)topupViewDidDisAppear {
    [self analyticsEvent8];
}

//支付宝支付
-(void)XLNewZFBZHIFU:(UIButton *)zfbBtn;
{
    
    if (!([self.myMoney integerValue] > 0)) {
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
    } else {
        [self analyticsEvent7];
        self.actionType = @"1";
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[[XLHTTPSessionManager sharedManager] getZFBPlayOrder:self.userInfoModel.Id giftId:@"1" TransType:self.actionType payType:@"4" FeeType:@"" Money:self.myMoney PrivateInfo:zhf_PrivateKey Remarks:RemarksRose Months:@"0" secretKey:self.userInfoModel.SecretKey] subscribeNext:^(id x) {
            BMHLog(@"===支付宝创建订单===%@",x);
            NSString * success = [NSString stringWithFormat:@"%@",x[@"success"]];
            self.payorder      = [NSString stringWithFormat:@"%@",x[@"data"]];
            if ([success isEqualToString:@"0"]) {
                NSString *money = [NSString stringWithFormat:@"%.2f", [self.myMoney floatValue]];
//                [ZhifuHelp InPutzhifubaoWithDingdan:self.payorder Money:money subjesct:RemarksRose body:RemarksRose successBlock:^{
//                    
//                    [self.navigationController popViewControllerAnimated:YES];
//                    
//                } failBlock:^{
//                    
//                    [self.navigationController popViewControllerAnimated:YES];
//                }];
                
                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                
            } else {
                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            
        } error:^(NSError *error) {
            NSLog(@"错误:%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showContent:@"加载失败,请重试!" toView:self.view];
            
        }];
    }
}

//AppstorePay(内购)
-(void)xlAppstorePay:(UIButton *)payBtn
{
    [self hadenlTopUpIn_purchase:payBtn];
}

#pragma mark AppStore内购支付订单
- (void)hadenlTopUpIn_purchase:(UIButton *)sender {
    if (!([self.myMoney integerValue] > 0)) {
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
    } else {
        
        self.actionType = @"1";
        [MBProgressHUD showMessage:nil];
        NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *actionType = self.actionType;
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@%@",objID, uid, publicKey, actionType, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        self.zfbDic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"Type",uid,@"Userid",@"1",@"Giftid",self.actionType,@"Transtype",@"6",@"Paytype",@"",@"Feetype",self.myMoney,@"Money",zhf_PrivateKey,@"Privateinfo",RemarksRose,@"Remarks",@"0",@"Months",locationString,@"Timestamp",nat,@"Appsign",kAppTypeOrId,@"appid",KAPPFr,@"qudao",nil];
        
        [BMHHTTPSession GET:@"/MobileInterface/Pay/AliPay.ashx" paraments:self.zfbDic success:^(id  _Nullable JSON) {
            NSLog(@"===苹果内购创建订单===%@",JSON);
            NSString *errcode = JSON[@"result"][@"errcode"];
            self.payorder = JSON[@"result"][@"OrderNo"];
            if ([errcode isEqualToString:@"0"]) {
                self.productIds= [NSString stringWithFormat:@"XLVideoChat%@",self.myMoney];
                if([SKPaymentQueue canMakePayments])
                {
                    //buy AppStore Products
                    [[BMHStoreObserver sharedInstance] buy:self.productIds withPayMonyNum:self.myMoney andPayOrder:self.payorder];
                    self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                    
                }else
                {
                    BMHLog(@"不允许程序内付费");
                }
                
            } else {
                
                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
            }
            
            [MBProgressHUD hideHUD];
        } failure:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
        }];
    }
}


#pragma mark - CallEvent
- (void)chatWithModel:(HomeCallModel *)model {
    NSString *uid = [[XLAccountManager shareInstance] model].Id;
    NSString *peeridStr = model.UserId;
    
    NSDate * senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    
    NSString *sTimeUser = [fmt stringFromDate:now];
    NSString *objIDUser = @"0";
    NSString *publicKeyUser = @"BMH2014YDYWB";
    NSString *natUser = [NSString stringWithFormat:@"%@%@%@%@%@",objIDUser,uid,peeridStr, publicKeyUser, sTimeUser];
    natUser = [natUser md5Encrypt];
    
    NSString *free = @"0";
    NSDictionary * videoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"6",@"Type",uid,@"Userid",peeridStr,@"Anchorid", @"2",@"Rtype",locationString,@"Timestamp",natUser,@"Appsign", free, @"isFree",nil];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:videoDic success:^(id  _Nullable JSON) {
        NSString * errcode  = JSON[@"result"][@"errcode"];
        NSString * videoID =  JSON[@"result"][@"data"][@"Id"];
        
        if ([errcode isEqualToString:@"0"])
        {
            NSString * callID =  [NSString stringWithFormat:@"%@",JSON[@"result"][@"data"][@"CallID"]];
            
            NSUser_save(videoID,kVideoID);//创建通话ID
            NSUser_save(callID,ChatToChatCallId);//创建通话ID
            
            //[HelpTool startTipViewWithText:@"通话发起成功!" duration:2.0f type:kTipViewTypeNone];
//            CallMakeViewController *make = [[CallMakeViewController alloc] init];
//            make.peerId = [NSString stringWithFormat:@"%@",model.UserId];
//            make.headStr = model.HeadImg;
//            make.nickNameStr = model.NickName;
//            make.detailStr = [NSString stringWithFormat:@"%@ %@",model.HostCity,model.job];
//            make.addressStr = model.HostCity;
//            make.ageStr = model.Age;
//            make.jobStr = model.job;
//            make.ismic = YES;
//            make.iscinema = YES;
//            make.callid = callID;
//            make.videoid = [NSString stringWithFormat:@"%@",videoID];
//            make.moneyStr = @"20";
//            make.gradeStr = [NSString stringWithFormat:@"%@",model.BGradeIcon];
//            
//            [self presentViewController:make animated:YES completion:nil];
            
        }else if ([errcode isEqualToString:@"-2"])
        {
            //[HelpTool startTipViewWithText:@"你的账号余额不足，请充值！" duration:2.0f type:kTipViewTypeNone];
            [self analyticsEvent5];
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
            
        }else if ([errcode isEqualToString:@"-10"])
        {
            [HelpTool startTipViewWithText:@"您的通话发起失败,请重新发起!" duration:2.0f type:kTipViewTypeNone];
            
        }else if ([errcode isEqualToString:@"-3"])
        {
            [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:[NSString stringWithFormat:@"%@",model.UserId]];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
                
            }];
            
        }else if ([errcode isEqualToString:@"-4"])
        {
            [HelpTool startTipViewWithText:@"已成为黑名单用户" duration:2.0f type:kTipViewTypeNone];
            
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"===创建通话====%@",JSON);
    } failure:^(NSError * _Nullable error) {
        NSLog(@"===创建通话失败===%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
}

#pragma mark - BMHVideoPlayerControlDelegate
- (void)videoPlaybackDidFinish {
    [self removePlayerView];
    [self hintViewSecond];
    self.hintSecondTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(hintSecond) userInfo:nil repeats:NO];
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
//
//
//
//        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
//    }
    
}

-(void)hintSecond
{
    self.hintSecondView.hidden = YES;
}

- (void)removePlayerView {
    [self.playerView shutDownPlayer];
    [self.playerView removeFromSuperview];
}
- (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

-(void)mineBtnAction:(UIButton * )mineBtn
{
    //我的page
    [self analyticsEvent4];
    XLMineViewController * mineVC = [[XLMineViewController alloc] init];
    [self.navigationController pushViewController:mineVC animated:YES];
    
}
- (void)messageAction:(id)sender {
    //消息page
    [self analyticsEvent3];
    ConversationListViewController *vc = [[ConversationListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }
    
    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [self presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}




 #pragma mark - 界面的滑动
 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
     
      self.isBeginSlid = YES;
 }
 
 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 
 //    1.获取手指
       UITouch *touch = [touches anyObject];
 //    2.获取触摸的上一个位置
       CGPoint lastPoint;
       CGPoint currentPoint;
 
 //    3.获取偏移位置
       CGPoint tempCenter;
 
       if (self.isBeginSlid) {//首次触摸进入
           lastPoint    = [touch previousLocationInView:self.playerView];
           currentPoint = [touch locationInView:self.playerView];
 
 
 //判断是左右滑动还是上下滑动
      if (ABS(currentPoint.x - lastPoint.x) > ABS(currentPoint.y - lastPoint.y)) {
 //    3.获取偏移位置
       tempCenter = self.playerView.center;
       tempCenter.x += currentPoint.x - lastPoint.x;//左右滑动
        //禁止向左划
//       if (self.playerView.frame.origin.x == 0 && currentPoint.x -lastPoint.x > 0) {//滑动开始是从0点开始的，并且是向右滑动
//              self.playerView.center = tempCenter;
//
//           }else if(self.playerView.frame.origin.x > 0){
//
//             self.playerView.center = tempCenter;
//           }
 
      }else{
 //    3.获取偏移位置
          tempCenter = self.playerView.center;
          tempCenter.y += currentPoint.y - lastPoint.y;//上下滑动
          
          
          
           if (self.hostIndex == 0) {
               
               if (self.playerView.frame.origin.y == 0 && currentPoint.y-lastPoint.y > 0){
                   
                   //self.playerView.center = tempCenter;
                   //[MBProgressHUD showContent:@"已到顶部,往上滑!" toView:self.view];
                   //return;
                   self.playerView.center = tempCenter;
               }else{
                   
                   
                   self.playerView.center = tempCenter;
               }
               
               
           }else{
               
               self.playerView.center = tempCenter;
           }
          

          
         
         
      }
  }else{//滑动开始后进入，滑动方向要么水平要么垂直
       if (self.playerView.frame.origin.y != 0){//垂直的优先级高于左右滑，因为左右滑的判定是不等于0
 
          lastPoint = [touch previousLocationInView:self.playerView];
       currentPoint = [touch locationInView:self.playerView];
         tempCenter = self.playerView.center;
      tempCenter.y += currentPoint.y -lastPoint.y;
         self.playerView.center = tempCenter;
 }else if (self.playerView.frame.origin.x != 0) {
 
       lastPoint = [touch previousLocationInView:self.playerView];
       currentPoint = [touch locationInView:self.playerView];
       tempCenter = self.playerView.center;
 
       tempCenter.x += currentPoint.x -lastPoint.x;
 
 //禁止向左划
 
 if (self.playerView.frame.origin.x == 0 && currentPoint.x -lastPoint.x > 0) {//滑动开始是从0点开始的，并且是向右滑动
      self.playerView.center = tempCenter;
 
     }else if(self.playerView.frame.origin.x > 0){
     
        self.playerView.center = tempCenter;
      }
 
    }
  }
 
  self.isBeginSlid = NO;
 }
 
 - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 //    NSLog(@"%.2f-----%.2f",livingInfoView.frame.origin.y,Screen_height * 0.8);
 
 //    水平滑动判断
 //在控制器这边滑动判断如果滑动范围没有超过屏幕的十分之八livingInfoView还是离开屏幕
    if (self.playerView.frame.origin.x > XQScreenW * 0.8) {
       [UIView animateWithDuration:0.06 animations:^{
           CGRect frame = self.playerView.frame;
           frame.origin.x = XQScreenW;
           self.playerView.frame = frame;
       }];
        
      
 
 }else{//否则则回到屏幕0点
      [UIView animateWithDuration:0.2 animations:^{
           CGRect frame = self.playerView.frame;
           frame.origin.x = 0;
           self.playerView.frame = frame;
      }];
     
     
//     CGRect frame = self.playerView.frame;
//     frame.origin.x = 0;
//     self.playerView.frame = frame;
 }
 
 //    上下滑动判断
 if (self.playerView.frame.origin.y > XQScreenW * 0.2) {
        //切换到上一频道
     [self analyticsEvent7];
     [self.hintSecondTimer invalidate];
     self.hintSecondTimer = nil;
     self.hintSecondView.hidden = YES;
     [self transitionWithType:@"cube" WithSubtype:kCATransitionFromBottom ForView:self.playerView];
     if (self.dataArray) {
         
         if (self.hostIndex == 0) {
             [self makeData];
             self.hostIndex = 0;
        }else{
            
             self.hostIndex--;
        }
         
     }
     
     
     self.currentCamgirlModel = self.dataArray[self.hostIndex];
     [self playVideoWithCamgirlModel:self.currentCamgirlModel];
 
 }else if (self.playerView.frame.origin.y < - XQScreenW * 0.2){
 //切换到下一频道
     [self analyticsEvent6];
     [self.hintSecondTimer invalidate];
     self.hintSecondTimer = nil;
     self.hintSecondView.hidden = YES;
     [self transitionWithType:@"cube" WithSubtype:kCATransitionFromTop ForView:self.playerView];
     self.hostIndex++;
     BMHLog(@"第===%ld个主播",(long)self.hostIndex);
     if (self.dataArray) {
         NSInteger index = self.hostIndex % self.dataArray.count;
         if (index == 0) {
             
             [self loadMoreData];
             self.hostIndex = 0;
         }
         
     }

     self.currentCamgirlModel = self.dataArray[self.hostIndex];
     [self playVideoWithCamgirlModel:self.currentCamgirlModel];
 }
 //     回到原始位置等待界面重新加载
        CGRect frame = self.playerView.frame;
        frame.origin.y = 0;
        self.playerView.frame = frame;
 
 }
 

- (void)loadMoreData {
    self.pageIndex++;
    [[[XLHTTPSessionManager sharedXIUQUManager] getNewCamgirlBeautyListPageIndex:self.pageIndex type:@1 userID:[[XLAccountManager shareInstance] model].Id andSign:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
        NSMutableArray *tempArray = self.dataArray.mutableCopy;
        [tempArray addObjectsFromArray:x];
        self.dataArray = tempArray.copy;
    } error:^(NSError *error) {
        self.pageIndex--;
    }];
}

#pragma CATransition动画实现
- (void) transitionWithType:(NSString *) type WithSubtype:(NSString *) subtype ForView : (UIView *) view
{
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    
    //设置运动时间
    animation.duration = DURATION;
    
    //设置运动type
    animation.type = type;
    if (subtype != nil) {
        
        //设置子类
        animation.subtype = subtype;
    }
    
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    
    [view.layer addAnimation:animation forKey:@"animation"];
}


#pragma mark - analyticsEvent
- (NSDictionary *)genrateAttributes {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    if ([[XLAccountManager shareInstance] model].Id) {
        [attributes setObject:[[XLAccountManager shareInstance] model].Id ?: @"" forKey:@"userid"];
    }
    if (self.currentCamgirlModel.UserId) {
        [attributes setObject:self.currentCamgirlModel.UserId ?: @"" forKey:@"camgirlid"];
    }
    return attributes.copy;
}

- (void)analyticsEvent1 {//进入老用户首页
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_oldindex" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"xl_oldindex" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent2 {//视频聊天按钮
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_videochat" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_click_videochat" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent3 {//消息
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_message" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_click_message" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent4 {//我的
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_headimg" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_click_my" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent5 {//弹出"充值界面"
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_charge" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_popup_charge" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent6 {//向上滑动
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_slide_right" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_slide_up" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent7 {//向下滑动
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_slide_left" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_slide_down" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent8 {//点击“充值界面”弹层中的取消
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_slide_left" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_click_chargecancel" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent9 {//点击“充值界面”中去充值按钮
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_slide_left" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_click_chargego" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent10 {//充值返回统计
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_slide_left" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_oldindex" action:@"old_charge_back" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
